package com.jiangjiang.eshop.inventory.async;

import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @ClassName OfflineResumeThread
 * @Description TODO
 * @Author jhw
 * @Date 2021/6/14 17:45
 * @Version 1.0
 **/
@Slf4j
public class OfflineResumeThread extends Thread {

    /**
     * 离线存储管理器
     */
    private OfflineStorageManager offlineStorageManager;

    /**
     * 库存更新队列
     */
    private StockUpdateQueue stockUpdateQueue;

    /**
     * 构造函数
     * @param offlineStorageManager 离线存储管理组件
     */
    public OfflineResumeThread(OfflineStorageManager offlineStorageManager,
                               StockUpdateQueue stockUpdateQueue) {
        this.offlineStorageManager = offlineStorageManager;
        this.stockUpdateQueue = stockUpdateQueue;
    }

    @Override
    public void run() {
        try {
            OfflineStorageIterator iterator = offlineStorageManager.iterator();
            while (iterator.hasNext()){
                List<StockUpdateMessage> messages = iterator.next();
                // 将这批数据写入内存队列中
                for(StockUpdateMessage message : messages) {
                    stockUpdateQueue.putDirect(message);
                }
                // 批量删除这批数据
                offlineStorageManager.removeByBatch(messages);
            }
            // 此时mysql中的数据全部恢复完，更新内存标识
            offlineStorageManager.setOffline(false);
        }catch (Exception e){
            log.warn("error", e);
        }
    }
}
